import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Alert } from 'react-native';
import {
  getToken,
  saveToken,
  getUserInfo,
  saveUserInfo,
  clearAuthStorage
} from './tokenStorage';
import apiService from '../../services/api';

// 用户信息接口
export interface User {
  id: string;
  userId: string;
  name: string;
  email: string;
  role?: string;
  orgId?: string;
  orgName?: string;
}

// 认证上下文接口
interface AuthContextType {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  login: (userId: string, password: string) => Promise<boolean>;
  logout: () => Promise<void>;
  clearError: () => void;
  error: string | null;
}

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者属性接口
interface AuthProviderProps {
  children: ReactNode;
}

// 认证提供者组件
export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 在应用启动时检查已存储的认证信息
  useEffect(() => {
    const loadStoredAuth = async () => {
      try {
        const storedToken = await getToken();
        if (storedToken) {
          const storedUser = await getUserInfo();
          if (storedUser) {
            setUser(storedUser);
          }
        }
      } catch (err) {
        console.error('加载存储的认证信息失败:', err);
      } finally {
        setIsLoading(false);
      }
    };

    loadStoredAuth();
  }, []);

  // 登录函数
  const login = async (userId: string, password: string): Promise<boolean> => {
    setIsLoading(true);
    setError(null);

    try {
      console.log('尝试登录...');

      // 使用API服务进行登录
      const userData = await apiService.auth.login(userId, password);

      if (!userData || !userData.user) {
        throw new Error('登录失败：无效的响应数据');
      }

      // 存储用户信息和令牌
      await saveUserInfo(userData.user);
      await saveToken(userData.token || '');

      // 更新状态
      setUser(userData.user);
      console.log('登录成功:', userData.user.name);
      return true;
    } catch (err: any) {
      setError(err.message || '登录过程中发生错误');
      console.error('登录错误:', err);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 登出函数
  const logout = async (): Promise<void> => {
    setIsLoading(true);
    try {
      console.log('执行登出...');

      try {
        // 使用API服务进行登出
        await apiService.auth.logout();
      } catch (err) {
        // 即使服务端登出失败，我们仍然会清除本地存储
        console.warn('服务端登出请求失败，但会继续清除本地会话');
      }

      // 清除本地存储
      await clearAuthStorage();
      setUser(null);
      console.log('登出成功');
    } catch (err) {
      console.error('登出错误:', err);
      Alert.alert('错误', '登出过程中发生错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 清除错误
  const clearError = () => setError(null);

  // 创建上下文值
  const contextValue: AuthContextType = {
    user,
    isLoading,
    isAuthenticated: !!user,
    login,
    logout,
    error,
    clearError,
  };

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  );
}

// 使用认证上下文的钩子
export function useAuth(): AuthContextType {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth 必须在 AuthProvider 内部使用');
  }
  return context;
}